﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Itfort.Net;

namespace Users.SnsConnect
{
	public class OAuth2Client
	{
		public string client_id;
		public string client_secret;
		public string response_type;
		public string grant_type;
		public string code;
		public string redirect_uri;
		public string scope;
		public string state;
		public string view;

		public string auth_uri;
		public string token_uri;

		public OAuth2Client()
		{
			response_type = "code";
			grant_type = "authorization_code";
		}

		public string GetFullAuthUrl()
		{
			StringBuilder url = new StringBuilder(auth_uri);
			if (!auth_uri.Contains('?'))
			{
				url.Append("?client_id=" + client_id);
			}
			else
			{
				url.Append("&client_id=" + client_id);
			}

			url.Append("&response_type=" + response_type);
			url.Append("&redirect_uri=" + HttpUtility.UrlEncode(redirect_uri));
			if (scope != null)
			{
				url.Append("&scope=" + scope);
			}
			if (state != null)
			{
				url.Append("&state=" + state);
			}
			if (view != null)
			{
				url.Append("&view=" + view);
			}

			return url.ToString();
		}

		public string GetFullTokenUrl()
		{
			StringBuilder url = new StringBuilder(token_uri);
			if (!token_uri.Contains('?'))
			{
				url.Append("?client_id=" + client_id);
			}
			else
			{
				url.Append("&client_id=" + client_id);
			}

			url.Append("&client_secret=" + client_secret);
			url.Append("&grant_type=" + grant_type);
			url.Append("&code=" + code);
			url.Append("&redirect_uri=" + HttpUtility.UrlEncode(redirect_uri));

			if (scope != null)
			{
				url.Append("&scope=" + scope);
			}
			if (state != null)
			{
				url.Append("&state=" + state);
			}
			if (view != null)
			{
				url.Append("&view=" + view);
			}

			return url.ToString();
		}

		public void RedirectToAuth()
		{
			HttpContext.Current.Response.Redirect(GetFullAuthUrl());
		}

		public string ExchangeAccessToken()
		{
			Uri uri = new Uri(GetFullTokenUrl());
			string text = HttpClient.PostHtml(uri, "", Encoding.UTF8);
			return text;
		}

		public string ExchangeAccessToken(string httpMethod)
		{
			Uri uri = new Uri(GetFullTokenUrl());
			string text = HttpClient.RequestContent(uri, httpMethod, Encoding.UTF8);
			return text;
		}
	}
}
